<template>
  <div class="merchant-apply">
    <!-- 认证状态卡片展示 -->
    <div v-if="status !== null" class="status-card">
      <el-card class="status-card-container" shadow="hover">
        <h3 class="status-title">认证状态</h3>
        <el-alert
            :title="statusMessage"
            :type="statusType"
            show-icon
        ></el-alert>
      </el-card>
    </div>

    <!-- 表单内容 -->
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" :disabled="isFormDisabled">
      <el-form-item label="商店名称" prop="storeName">
        <el-input v-model="form.storeName" placeholder="请输入商店名称"></el-input>
      </el-form-item>

      <el-form-item label="营业执照" prop="license">
        <el-upload
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            list-type="picture-card"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            :disabled="isFormDisabled"
            accept="image/*"
        >
        <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="商店描述" prop="description">
        <el-input type="textarea" v-model="form.description" placeholder="请输入商店描述" :disabled="isFormDisabled"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm" :disabled="isFormDisabled">提交申请</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ElMessage, ElAlert, ElCard } from "element-plus";
import request from "@/utils/request"; // 使用封装的请求方法

export default {
  data() {
    return {
      form: {
        storeName: "",
        license: "",
        description: "",
      },
      rules: {
        storeName: [{ required: true, message: "请输入商店名称", trigger: "blur" }],
        license: [{ required: true, message: "请上传营业执照", trigger: "change" }],
        description: [{ required: true, message: "请输入商店描述", trigger: "blur" }],
      },
      status: null, // 认证状态：null表示未提交, "审核中", "已通过", "已拒绝"
      isFormDisabled: false, // 控制表单是否禁用
    };
  },
  created() {
    this.checkCertificationStatus(); // 页面加载时检查认证状态
  },
  methods: {
    // 检查认证状态
    checkCertificationStatus() {
      const aId = JSON.parse(localStorage.getItem("xm-pro-user")).id; // 获取当前用户的 aId
      request
          .get(`/merchant/status/${aId}`) // 调用正确的接口查询认证状态
          .then((res) => {
            if (res.code === 200) {
              const statusData = res.data;
              this.status = statusData.status; // status could be 'pending', 'approved', or 'rejected'
              this.isFormDisabled = statusData.status === "pending" || statusData.status === "approved"; // 禁用表单
            } else {
              ElMessage.error("获取认证状态失败");
            }
          })
          .catch((error) => {
            ElMessage.error("获取认证状态失败");
            console.error(error);
          });
    },

    // 文件上传成功时的回调
    handleSuccess(response, file, fileList) {
      this.form.license = file.url || ''; // 假设文件上传后返回了文件的 URL
    },

    // 在上传前进行的检查
    beforeUpload(file) {
      const isImage = file.type === "image/jpeg" || file.type === "image/png";
      if (!isImage) {
        ElMessage.error("只能上传 JPG/PNG 格式的图片");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        ElMessage.error("上传图片大小不能超过 2MB!");
      }
      return isImage && isLt2M;
    },

    // 文件预览
    handlePreview(file) {
      console.log("preview", file);
    },

    // 删除文件时的处理
    handleRemove(file, fileList) {
      console.log("remove", file, fileList);
    },

    // 提交表单
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 提交商户认证申请
          const aId = JSON.parse(localStorage.getItem("xm-pro-user")).id;
          request
              .post("/merchant/apply", {
                aId,
                storeName: this.form.storeName,
                license: this.form.license,
                description: this.form.description,
              })
              .then((res) => {
                if (res.code === 200) {
                  ElMessage.success("认证申请提交成功！");
                  this.checkCertificationStatus(); // 提交后刷新认证状态
                } else {
                  ElMessage.error("提交失败：" + res.msg);
                }
              })
              .catch((error) => {
                ElMessage.error("提交申请失败，请稍后重试！");
                console.error(error);
              });
        }
      });
    },
  },
  computed: {
    // 根据认证状态动态显示提示消息
    statusMessage() {
      if (this.status === "pending") {
        return "您的认证申请正在审核中";
      } else if (this.status === "approved") {
        return "恭喜！您的认证申请已通过";
      } else if (this.status === "rejected") {
        return "您的认证申请未通过，具体原因请联系管理员";
      }
      return "您尚未提交认证申请";
    },
    // 动态设置状态颜色
    statusType() {
      if (this.status === "pending") {
        return "info";
      } else if (this.status === "approved") {
        return "success";
      } else if (this.status === "rejected") {
        return "error";
      }
      return "warning";
    },
  },
};
</script>

<style scoped>
.merchant-apply {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}

.status-card-container {
  margin-bottom: 20px;
}

.status-title {
  font-size: 20px;
  color: #333;
  margin-bottom: 10px;
}

.status-message {
  margin-bottom: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-button {
  width: 100%;
}

.el-upload {
  border: 1px dashed #dcdfe6;
  padding: 10px;
  text-align: center;
  cursor: pointer;
}
</style>
